const express = require("express")
const session = require("express-session")
const mysql = require("mysql")
const jsSHA = require("jssha") //引入sha加密
const app = express()

// 连接数据库
const db = mysql.createPool({
  host: "localhost",
  user: "root",
  password: "123456",
  database: "shop"
})

app.use(express.urlencoded({extended : false})) // 配置之后 req.body 可正常显示 x-www-form-urlencoded
app.use(session({
  secret: 'anyString', // 任意字符串
  resave: false,
  saveUninitialized: true
}))

app.post('/login', (req, res) => {
  // 查询数据库
  const sqlStr = 'select count(*) as total from shop_admin where name=? and password=?'
  // 将传过来的密码转为sha-1加密的哈希值 因为数据库中的也是sha-1加密
  const shaObj = new jsSHA("SHA-1","TEXT",{encoding:"UTF8"})
  shaObj.update(req.body.password)
  const passwordSha = shaObj.getHash("HEX")
  console.log(passwordSha)
  
  db.query(sqlStr, [req.body.username, passwordSha], (err, results) => {
    console.log(results[0].total)
    if (err) {
      console.log(err)
    } else if(results[0].total === 1) {
      // 设置session
      req.session.user = req.body
      req.session.isLoggedIn = true
      // 响应客户端
      res.send(`用户${req.body.username}登陆成功`)
      console.log(`用户${req.body.username}登陆成功`)
    } else {
      res.send('账号或密码错误')
      console.log('账号或密码错误')
    }
  })
})

app.listen(8088, () => {
  console.log('running')
})

